from datetime import datetime,timedelta

import requests
import sqlalchemy
from flask import Blueprint, jsonify, request, session
from flask_jwt_extended import jwt_required
from sqlalchemy import func, cast, desc
from exts import mail, db
from server.resource.util.MD5 import md5_encrypt,md5_verify
from models import EmailCaptchaaModel, UserModel, IncomeModel, TestReport, TestRecord
from server.resource.util.ApiResponse import ApiResponse
from flask_mail import Message
import string
import random

bp = Blueprint("TestReport",__name__,url_prefix="/testReport")

@bp.route('/add', methods=['POST'])
def add():

    data = request.get_json()
    image_url = data['image_url']
    report_name = data['report_name']

    #跑模型
    image_url1,image_url2,image_url3,image_url4,ela_probability,dct_probability,rgbn_probability,iml_probability = run(image_url)

    #形成pdf报告
    api_url = "http://api.tp.zzzsleep.icu/PDF/get"
    response = requests.post(api_url, json={'image_url': image_url,
                                            'ela_url':image_url1,
                                            'dct_url':image_url2,
                                            'rgbn_url':image_url3,
                                            'iml_url':image_url4,
                                            'ela_probability':ela_probability,
                                            'dct_probability': dct_probability,
                                            'rgbn_probability': rgbn_probability,
                                            'iml_probability': iml_probability
                                            })  # 发送JSON数据
    print(response)
    response_data = response.json()
    my_pdf = response_data.get('pdf_link')
    print(my_pdf)

    #写入test_report表
    # username = session.get('username')
    username = 'bingbing'
    test_report = TestReport(url = my_pdf,username=username)
    db.session.add(test_report)
    db.session.commit()

    #取ID：
    test_report2 = TestReport.query.filter_by(url = my_pdf,username=username,is_delete=0).first()
    test_report_id = test_report2.id

    # test_record+1
    # username = session.get('username')
    username = 'bingbing'
    user = UserModel.query.filter_by(username=username).first()
    member_state = user.member_state
    url = my_pdf
    test_record = TestRecord(username=username,member_state=member_state,url=url,TestReport_id=test_report_id,report_name = report_name)
    db.session.add(test_record)

    db.session.commit()

    return jsonify(ApiResponse.success())

def run(image_url):
    api_url = "http://api.tp.zzzsleep.icu/ELA/get"
    response = requests.post(api_url, json={'image_url': image_url})  # 发送JSON数据
    if response.status_code == 200:
        response_data = response.json()
        data1 = response_data.get('data')
        image_url1 = data1['image_url']
        ela_probability = data1['probability']
        print(ela_probability)

    api_url = "http://api.tp.zzzsleep.icu/DCT/get"
    response = requests.post(api_url, json={'image_url': image_url})  # 发送JSON数据
    if response.status_code == 200:
        response_data = response.json()
        data2 = response_data.get('data')
        image_url2 = data2['image_url']
        dct_probability = data2['probability']
        print(dct_probability)

    api_url = "http://api.tp.zzzsleep.icu/A3/get"
    response = requests.post(api_url, json={'image_url': image_url})  # 发送JSON数据
    if response.status_code == 200:
        response_data = response.json()
        data3 = response_data.get('data')
        image_url3 = data3['image_url']
        rgbn_probability = data3['probability']
        print(rgbn_probability)

    api_url = "http://api.tp.zzzsleep.icu/A4/get"
    response = requests.post(api_url, json={'image_url': image_url})  # 发送JSON数据
    if response.status_code == 200:
        response_data = response.json()
        data4 = response_data.get('data')
        image_url4 = data4['image_url']
        iml_probability = data4['probability']
        print(iml_probability)

    return image_url1,image_url2,image_url3,image_url4,ela_probability,dct_probability,rgbn_probability,iml_probability


@bp.route('/getAll', methods=['POST'])
def getAll():
    data = request.get_json()
    username = data['username']

    # 检查用户名是否提供
    if not username:
        return jsonify(ApiResponse.server_error('用户名不能为空'))

    try:
        # 查询数据库
        test_records = TestRecord.query \
            .filter_by(username=username, is_delete=0) \
            .order_by(desc(TestRecord.join_time)) \
            .all()
    except Exception as e:
        # 处理查询错误
        return jsonify(ApiResponse.server_error(str(e)))

    # 初始化响应数据列表
    response_data = []

    for test_record in test_records:
        record = {
            'url': test_record.url,
            'state': test_record.state,
            'join_time': test_record.join_time.strftime('%Y-%m-%d %H:%M:%S'),
            'report_name':test_record.report_name
        }
        response_data.append(record)

    # 返回成功的响应
    return jsonify(ApiResponse.success(response_data))


